<!--
 * @Author: yangzhiyu yangzhiyu@mail.pigcms.com
 * @Date: 2024-03-05 13:59:35
 * @LastEditors: yangzhiyu yangzhiyu@mail.pigcms.com
 * @LastEditTime: 2024-03-18 15:21:26
 * @FilePath: \fe_user_pc\src\views\shotstack\CreationCenter\AddVideoIntelligentSplit.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="smart-clip">
    <div>
      <div style="display: flex; height: 32px; line-height: 32px;justify-content: space-between;">
        <div class="flex">
          <RouteTitle :isBack="true" />
        </div>
        <a-button type="primary" @click="toViewList">拆分记录</a-button>
      
      </div>
    </div>
    <div class="ai-wirting mt-20">
      <a-card>
        <!-- 测试FFmpeg -->
        <!-- <input type="file" @change="handleFileUpload" accept="video/*" />
        <div ref="canvasContainer"></div> -->

        <a-form layout="horizontal">
          <a-form-item label="拆分方式">
            <a-radio-group v-model:value="radioValue">
              <a-radio v-for="(item, index) in splitType" :key="index" :value="item.value">
                {{ item.label }}
              </a-radio>
            </a-radio-group>

            <span v-if="radioValue == 'scene_auto'">
              <a-popover placement="top">
                <template #content>
                  <span style="font-size: 12px; margin: 0 0 5px 3px">按照视频转场进行智能拆分</span>
                </template>

                <question-circle-outlined />
              </a-popover>
            </span>
          </a-form-item>
          <a-form-item label="间隔时间" v-if="radioValue == 'interval'">
            <a-input-number v-model:value="timeInput" style="width: 200px" :min="1" :max="99.99">
              <template #addonAfter> 秒 </template>
            </a-input-number>
          </a-form-item>
          <a-form-item label="视频来源">
            <a-radio-group v-model:value="radioValueT">
              <a-radio value="Network"> 网络视频</a-radio>

              <a-radio value="Library"> 素材库视频 </a-radio>
            </a-radio-group>
          </a-form-item>
          <div class="tip text-gray-5"  v-if="radioValueT == 'Network'">
              输入视频分享链接，一键智能视频解析，提取视频。支持平台：{{pList.join('、')}}。
            </div>
          <a-form-item label="视频链接" v-if="radioValueT == 'Network'">
            
            <a-textarea v-model:value="internetVideoUrl" placeholder="请粘贴抖音视频链接，视频时长建议不超过20分钟" style="
                width: 450px;
                height: 100px;
                resize: none;
                border-radius: 5px;
              "></a-textarea>
          </a-form-item>

          <a-form-item label="视频素材" v-else>
            <a-card v-if="!currentVideo?.material_url">
              <a-button type="primary" @click="showAddModal"><plus-outlined />添加成片</a-button>
              <div class="upload-wrapper">
                <div class="upload-content" @click="showAddModal">
                  <cloud-upload-outlined />
                  <span class="text-16 text-gray-5">添加视频</span>
                </div>
              </div>
            </a-card>
            <div class="video_con" v-else>
              <video id="videoPlayer" :src="currentVideo?.material_url" autoplay />
              <div class="operate_con">
                <cu-icon @click="deleteVideo" type="icon-shanchu1" class="delete_icon" />
              </div>
            </div>
          </a-form-item>
        </a-form>
        <div style="margin-left: 70px">
          <!-- {{ clipRole.includes('spzncf') }} -->
          <a-tooltip v-if="!clipRole.includes('spzncf')" placement="topLeft">
            <template #title>
              <span>套餐不支持该权限</span>
            </template>
            <a-button type="primary" :loading="btnLoading">开始拆分</a-button>
          </a-tooltip>

          <a-button v-else type="primary" @click="toSplit" :loading="btnLoading">开始拆分</a-button>

          <div class="mt-5" style="color:#666">
            <!-- 每拆分{{ all_min }}分钟的素材,将消耗{{ consumes }}{{ unit
            }}{{ point_name }} -->

            每分钟消耗{{init_consumes }}{{ unit
            }}{{ point_name }}(不足1分钟按1分钟计算)
          </div>
        </div>
      </a-card>
    </div>

    <ChooseMaterial :isClip="false" material_type="video" :visible="addVisible" @close="cancel" />

    <!-- <newChooseMaterial
    :isClip="true"
    :visible="addVisible"
    modelType = "video"
    @close="cancel"
    /> -->
    <!-- 加载中弹窗 -->
    <lodingModel ref="loding" :btnConfig="{
        show: true,
        text: '稍后查看',
        isDanger: true,
      }" :contentText="'素材拆分中...'" :baseIncrement="2" detailed="可稍后在列表中查看并进行下一步操作" @cancel="toVideoList"
      :marskClose="true"></lodingModel>

    <!-- 提示弹窗 -->
    <baseModel ref="dialog">
      <template #title>
        <span style="font-size: 18px; font-weight: 500">确定拆分</span>
      </template>
      <template #content>
        <div style="font-size:14px;font-weight: 600;">
          <span>您剩余的{{ countData?.numberInfo.name }} {{ countData?.pointInfo.name }}为<span style="color: red;">{{
              countData?.pointInfo?.current }}</span>{{ countData?.pointInfo.unit }} </span>，
          <span>本次消耗{{ countData?.pointInfo.name }}<span style="color: #4b93f9;"> {{ countData?.pointInfo.consumes
              }}</span>{{ countData?.pointInfo.unit
            }}</span>
        </div>

        <!-- <span style="color: #108ee9">
          {{ consumes }}{{ unit }}{{ point_name }}</span
        >
        <span
          >，点击确定后将扣除相应的{{ point_name }}，请确保{{
            point_name
          }}充足（若拆分失败将返还消耗的{{ point_name }})</span
        > -->

      </template>
      <template #footer>
        <a-button key="back" @click="dialog.closeModal()">取消</a-button>
        <a-button key="submit" type="primary" :loading="hintLoading" @click="debouncedClick"
          class="submitBtn">确定</a-button>
      </template>
    </baseModel>
  </div>

  <!-- 保存到文件夹弹窗@selfSubmit="saveVideoData"  -->
  <MaterialsModule ref="materials" jobCategory="videoSplit" :splitVideoId="splitVideoId" :aisave="false"
    :StoryboardSplit="true" :requestType="true" :material_type="'video'" @saveMethod="saveFn"
    @selfRequest="saveVisible = false" @getMerchant_folder_statck_id="getMerchant_folder_statck_id"
    :visible="saveVisible" :data="currentSaveData" @onCancel="saveVisible = false" />

  <!-- 充值弹窗 -->
  <vipModal ref="vipModalRef" :visible="vipVisible" @close="vipVisible = false"></vipModal>
</template>

<script>
import {
  reactive,
  toRefs,
  watch,
  computed,
  ref,
  watchEffect,
  onMounted,
  onUnmounted,
} from "vue";
import { useRouter } from "vue-router";

// import MaterialLibrary from "../components/MaterialLibrary.vue";
import request from "@/common/utils/request";
import utils from "@/common/utils/utils";
import { getCurrentTeam } from "@/common/utils/storage";
import {
  CloudUploadOutlined,
  PlusOutlined,
  QuestionCircleOutlined,
} from "@ant-design/icons-vue";
import AddClipping from "./modules/AddClipping.vue";
import ChooseMaterial from "../EditingCenter/modules/bottomSet/components/chooseMaterial.vue";
import newChooseMaterial from "@/views/shotstack/EditingCenter/modules/bottomSet/components/newChooseMaterial.vue";

import { message, notification } from "ant-design-vue";
import store from "@/store/index.js";
import { platformList } from "./utils/index.js";
// 加载组件
import lodingModel from "@/components/lodingModel/lodingModel.vue";
// 提示框
import baseModel from "@/components/baseModel/baseModel.vue";
import MaterialsModule from "@/views/shotstack/components/MaterialsModule/materialLibraryModal.vue";
import { useStore } from "vuex";
// 充值弹窗
import vipModal from '@/socialMedia/Vip/vipModal.vue'

export default {
  name: "AiWriting",
  components: {
    vipModal,
    newChooseMaterial,
    CloudUploadOutlined,
    QuestionCircleOutlined,
    ChooseMaterial,
    PlusOutlined,
    lodingModel,
    baseModel,
    MaterialsModule,
  },
  setup() {
    const store = useStore();

    // 加载组件
    const loding = ref(null);
    // 询问弹窗
    const dialog = ref(null);
    const router = useRouter();
    // 按钮loading
    const btnLoading = ref(false);
    // 拆分提示loding
    const hintLoading = ref(false);
    // 网络视频生成的id
    const splitVideoId = ref("");
    // 充值弹窗开关
    const vipVisible = ref(false)
    const vipModalRef = ref(false)
    const state = reactive({
      internetVideoUrl: "",
      radioValue: "scene",
      radioValueT: "Library",
      addVisible: false,
      currentVideo: {},
      time: 5,
      pageData: {},
      timeoutId: null,
      splitType: {},
      merchant_folder_statck_id: "",
      debounceTimer: null,
      consumes: "1",
      init_consumes: "1",
      all_min: "1",
      unit: "",
      point_name: "",
      countData:null,
      pList:platformList,
    });

    // 监听 处理视频来源
    watch(
      () => state.radioValue,
      (val) => {
        if (val == "scene_auto") {
          state.radioValueT = "Library";
        }
      }
    );
    // 弹窗组件
    const materials = ref(null);
    // 保存弹窗开关
    const saveVisible = ref(false);
    // 保存弹窗数据
    const currentSaveData = ref({});
    // 打开选择视频弹框
    const showAddModal = () => {
      if (store.getters.isVersionExpired) {
        notification.warn({ message: "您的套餐已到期", duration: 2 });
        vipVisible.value = true;
    
      } else {
        state.addVisible = true;
      }
    };
    // 关闭弹框
    const cancel = (obj) => {
      console.log(obj,'素材');
      
      if (obj) {
        state.currentVideo = obj;
      }
      state.addVisible = false;
    };
    // 置空当前视频
    const deleteVideo = () => {
      state.currentVideo = {};
      store.dispatch('setSceneCreationSubtileTitles',{})
    };

    // 处理收集的time小数
    const timeInput = computed({
      get: () => {
        // 获取值时简单返回它
        return state.time;
      },
      set: (newValue) => {
        // 设定值时，确保最多只有两位小数
        // 如果newValue是空字符串或者其他非数值内容，则不更改time的值
        if (!isNaN(parseFloat(newValue)) && isFinite(newValue)) {
          state.time = parseFloat(parseFloat(newValue).toFixed(2));
        }
      },
    });

    const networkTime = ref(0);

    // 消耗的剪辑次数 - 网络视频默认为1条, 其余根据视频数量计算
    const videoLength = computed(() => {
      if (state.radioValueT == "Network") {
        // 视频的时长转换为秒（因为原始单位是毫秒）
        let durationInSeconds = networkTime.value / 1000;
        // 视频时长转换为分钟
        let durationInMinutes = durationInSeconds / 60;
        // 计算剪辑次数，每一分钟剪辑次数加1，超过一分钟整数的部分也向上取整
        let editCount = Math.ceil(durationInMinutes);
        // 确保最小剪辑次数为1
        return Math.max(editCount, 1);
      } else {
        // 视频的时长转换为秒（因为原始单位是毫秒）
        let durationInSeconds = state.currentVideo.material_duration / 1000;
        // 视频时长转换为分钟
        let durationInMinutes = durationInSeconds / 60;

        // 计算剪辑次数，每一分钟剪辑次数加1，超过一分钟整数的部分也向上取整
        let editCount = Math.ceil(durationInMinutes);
        // 确保最小剪辑次数为1
        return Math.max(editCount, 1);
      }
    });

    // 获取页面参数
    const getQueryObj = async () => {
      const data = {
        org_id: utils.getOrgId(),
        team_id: getCurrentTeam(),
        user_token: utils.getUserToken(),
      };
      const res = await request.get(
        "/work_ai",
        "/user/shotstack/video/video_to_clips/select",
        data
      );
      state.pageData = res.result;

      const newArray = Object.entries(res.result.split_type_select).map(
        (entry, index) => ({
          label: entry[1],
          value: entry[0],
        })
      );

      state.splitType = newArray;
      console.log(state.splitType, "splitType");
    };

    onMounted(() => {
      getQueryObj();
      if(Object.keys(store.getters.intelligentSplittingData).length){
        state.currentVideo = store.getters.intelligentSplittingData
      }
    });

    // 控制进度条显示
    const isShow = ref(false);

    // 开始拆分
    const toSplit = async () => {
      if (store.getters.isVersionExpired) {
        notification.warn({ message: "您的套餐已到期", duration: 2 });
        vipVisible.value = true;
      } else {

        if (state.radioValueT == "Network" && !state.internetVideoUrl) {
          // 视频链接
          message.warn("请先粘贴视频链接");
          return
        } else if (
          JSON.stringify(state.currentVideo) == "{}" &&
          state.radioValueT !== "Network"
        ) {
          message.warn("请先从素材库选择视频");
          return;
        } else if (state.timeoutId) {
          message.warn("当前已有正在执行的任务,稍后会自动前往列表页");
          return;
          // 网络视频并且不是分镜拆分, 选择文件夹,让后端拆分
        } 
        
                const res = await request.get(
          "/work_ai",
          "/user/shotstack/video_clip_split/config/get",
          { number: videoLength.value }
        );
        state.all_min = videoLength.value
        state.consumes = res.pointInfo.consumes;
        state.unit = res.pointInfo.unit;
        state.point_name = res.pointInfo.name;
        state.countData = res

        if (res?.usable != 1) {
          vipVisible.value = true
          vipModalRef.value && vipModalRef.value.openBuyVisible()
          return 
        }

        if (
          state.radioValueT == "Network" &&
          state.internetVideoUrl &&
          state.radioValue != "scene_auto"
        ) {
          btnLoading.value = true;
          // 获取视频时长
          try {
            const res = await request.post(
              "/work_ai",
              `/user/shotstack/video/get_time`,
              {
                video_url: state.internetVideoUrl,
              }
            );
            networkTime.value = res.result.material_duration;
            btnLoading.value = false;

            dialog.value.showModal();
          } catch (error) {
            btnLoading.value = false;
          }
        } else {
          // 分镜拆分
          if (state.radioValue == "scene_auto") {
            saveVisible.value = true;
          } else {
            dialog.value.showModal();
          }
        }
      }
    };

    // 按分镜拆分获取, 获取素材库传来的id
    const getMerchant_folder_statck_id = async (merchant_folder_statck_id) => {
      const data = {
        split_type: state.radioValue,
        video_url:
          state.radioValueT == "Network"
            ? // state.radioValueT == "Network" && state.radioValue == "scene_auto"
              state.internetVideoUrl
            : "",
        merchant_folder_statck_id,
        merchant_folder_statck_multimedia_id:
          state.radioValueT != "Network" ? state.currentVideo.id : 0,
        seconds: state.time + "",
      };
      const res = await request.post(
        "/work_ai",
        "/user/shotstack/video/video_to_clips",
        data
      );
      splitVideoId.value = res.id;
      console.log(res, "分镜拆分结果");
      message.success("保存成功！请等待处理完成!");
      saveVisible.value = false;
      setTimeout(() => {
        router.push({
          name: "VideoIntelligentSplitList",
        });
      }, 300);
    };

    const saveFn = (options) => {
      console.log('素材', options);
      
      if (options) {
        state.merchant_folder_statck_id = options;
      }
      saveVisible.value = false;
      setTimeout(() => {
        dialog.value.showModal();
      }, 500);
    };

    // 获取后台进度
    const getNext = async (id) => {
      if (!isShow.value) {
        // 传入'setInterval'代表需要自动增加进度
        loding.value.showModal("setInterval");
        isShow.value = true;
      }
      const videoData = await request.get(
        "/work_ai",
        `/user/shotstack/video/video_to_clips/detail?id=${id}`
      );

      // 判断是否是失败状态
      if (videoData.result.status_text == "拆分失败") {
        isShow.value = false;
        loding.value.closeModal();
        message.error("视频拆分失败, 请检查素材");
        return;
      }

      // 时间类型 0 完成, 口播类型1未完成 2 完成
      if (state.radioValue == "audio") {
        if (
          videoData.result.process_status !== 2 ||
          videoData.result.is_polling == 1
        ) {
          state.timeoutId = setTimeout(() => {
            getNext(id);
          }, 5000);
          return;
        }
      } else {
        if (
          videoData.result.process_status !== 0 ||
          videoData.result.is_polling == 1
        ) {
          setTimeout(() => {
            getNext(id);
          }, 5000);
          return;
        }
      }
      isShow.value = false;
      loding.value.closeModal();
      // 加载完成
      setTimeout(() => {
        router.push({
          name: "VideoSplit",
          query: {
            id: videoData.result.id,
            merchant_folder_statck_id: state.merchant_folder_statck_id,
          },
        });
      }, 400);
    };

    // 拆分组件, 点击按钮回调
    const toVideoList = () => {
      router.push({
        path: "videoIntelligentSplitList",
      });
    };

    // 询问是否继续, 确定按钮
    const onSubmit = async () => {
      // debugger
      const data = {
        split_type: state.radioValue,
        video_url:
          state.radioValueT == "Network"
            ? // state.radioValueT == "Network" && state.radioValue == "scene_auto"
              state.internetVideoUrl
            : "",
        merchant_folder_statck_id:
          state.radioValue == "scene_auto"
            ? state.merchant_folder_statck_id
            : state.radioValueT != "Network"
            ? state.merchant_folder_statck_id
            : 0,
        merchant_folder_statck_multimedia_id:
          state.radioValueT != "Network" ? state.currentVideo.id : 0,
        seconds: state.time + "",
      };
      if (state.radioValue !== "scene_auto") {
        // const data = {
        //   split_type: state.radioValue,
        //   video_url:
        //     state.radioValueT == "Network" ? state.internetVideoUrl : "",
        //   merchant_folder_statck_multimedia_id: state.radioValueT != "Network"
        //     ? state.currentVideo.id + ""
        //     : "",
        //   seconds: state.time + "",
        // };
        hintLoading.value = true;
        // 发送拆分请求
        try {
          const res = await request.post(
            "/work_ai",
            "/user/shotstack/video/video_to_clips",
            data
          );
          hintLoading.value = false;
          dialog.value.closeModal();
          if (!res.id) {
            // message.error("视频id不存在");
            return;
          }
          splitVideoId.value = res.id;
          getNext(res.id);
        } catch (error) {
          hintLoading.value = false;
          dialog.value.closeModal();
        }
      } else {
        try {
          hintLoading.value = true;

          // 发送拆分请求
          const res = await request.post(
            "/work_ai",
            "/user/shotstack/video/video_to_clips",
            data
          );
          hintLoading.value = false;
          dialog.value.closeModal();
          if (!res.id) {
            return;
          }
          splitVideoId.value = res.id;
          router.push({
            path: "videoIntelligentSplitList",
          });
        } catch (error) {
          hintLoading.value = false;
          dialog.value.closeModal();
        }
      }
    };

    const clipRole = ref([]);
    // 防抖
    const debouncedClick = () => {
      if (state.debounceTimer) {
        clearTimeout(state.debounceTimer);
      }

      state.debounceTimer = setTimeout(() => {
        onSubmit();
      }, 500);
    };

    // 取后台配置展示用
    const init = async () => {
      const res = await request.get(
        "/work_ai",
        "/user/shotstack/video_clip_split/config/get",
        { number: "1" }
      );
      state.init_consumes = res.pointInfo.consumes;
      state.unit = res.pointInfo.unit;
      state.point_name = res.pointInfo.name;
    };

    init();

    watch(
      () => store.state.user?.clipRole,
      (val) => {
        if (val) {
          clipRole.value = val;
        } else {
          clipRole.value = [];
        }
      },
      {
        deep: true,
        immediate: true,
      }
    );

    // 返回
    const goback = () => {
      router.push({
        name: "CreativityTools",
      });
    };
    // 查看拆分列表
    const toViewList = () => {
      router.push({
        name: "VideoIntelligentSplitList",
      });
    };

    onUnmounted(() => {
      if (state.timeoutId) {
        clearTimeout(state.timeoutId);
        state.timeoutId = null;
      }
    });

    // const handleFileUpload = async (event) => {
    //   const file = event.target.files[0];
    //   if (file) {
    //     await state.ffmpeg.load();
    //     state.ffmpeg.FS('writeFile', 'input.mp4', await fetchFile(file));

    //     // 提取帧
    //     await state.ffmpeg.run('-i', 'input.mp4', '-vf', 'fps=1', 'output%d.png');
    //     const files = state.ffmpeg.FS('readdir', '/');

    //     files.forEach((file) => {
    //       if (file.endsWith('.png')) {
    //         const data = state.ffmpeg.FS('readFile', file);
    //         const url = URL.createObjectURL(new Blob([data.buffer], { type: 'image/png' }));

    //         const img = new Image();
    //         img.src = url;
    //         img.onload = () => {
    //           const canvas = document.createElement('canvas');
    //           const context = canvas.getContext('2d');
    //           canvas.width = img.width;
    //           canvas.height = img.height;
    //           context.drawImage(img, 0, 0);
    //           this.$refs.canvasContainer.appendChild(canvas);
    //         };
    //       }
    //     });
    //   }
    // };

    return {
      ...toRefs(state),
      goback,
      vipVisible,
      vipModalRef,
      showAddModal,
      debouncedClick,
      cancel,
      deleteVideo,
      toSplit,
      getQueryObj,
      clipRole,
      getNext,
      toVideoList,
      onSubmit,
      saveFn,
      materials,
      currentSaveData,
      saveVisible,
      videoLength,
      timeInput,
      loding,
      dialog,
      btnLoading,
      networkTime,
      hintLoading,
      toViewList,
      splitVideoId,
      getMerchant_folder_statck_id,
    };
  },
};
</script>

<style lang="less" scoped>
.smart-clip {
  padding: 14px 14px 0;
  height: 100%;
  box-sizing: border-box;
}

.ss-input-number {
  border-radius: 5px;
}

button {
  border-radius: 5px;
}

:deep(.ss-select-selector) {
  border-radius: 0 5px 5px 0 !important;
}

.textarea-wrapper {
  border-radius: 5px;
}

input {
  border-radius: 5px;
}

:deep(.ss-card) {
  border-radius: 15px;
}

.submitBtn {
  border-color: var(--ss-primary-color);
  background-color: var(--ss-primary-color);

  &:hover {
    background-color: var(--ss-primary-color);
    border-color: var(--ss-primary-color);
  }
}

.upload-wrapper {
  width: 200px;
  height: 324px;
  margin: 20px 20px 20px 0;
  padding: 20px;
  background-color: #f3f4f6;
  border-radius: 15px;
}

.upload-content {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  font-size: 46px;
  width: 160px;
  height: 284px;
  background-color: #fff;
  border-radius: 15px;
  cursor: pointer;
}

.text-16 {
  font-size: 16px;
}

.video_con {
  width: 150px;
  height: 250px;
  background-color: #000;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;

  .operate_con {
    display: none;
  }

  &:hover {
    .operate_con {
      width: 150px;
      height: 250px;
      position: absolute;
      left: 0;
      top: 0;
      background-color: rgba(0, 0, 0, 0.3);
      display: flex;
      align-items: center;
      justify-content: center;

      .play_icon {
        color: #fff;
        font-size: 24px;
        cursor: pointer;

        &:hover {
          color: #2878ff;
        }
      }

      .delete_icon {
        color: #fff;
        font-size: 24px;
        cursor: pointer;

        &:hover {
          color: #2878ff;
        }
      }
    }
  }

  video {
    max-width: 100%;
    max-height: 100%;
  }
}

:deep(.ss-popover-placement-rightr) {
  position: absolute !important;
  left: 852px !important;
  top: 144px !important;
}

.disabled-tip {
  color: #ccc;
  font-size: 12px;
}
.tip{
  display: flex;
  align-items: center;
  height: 40px;
  margin-left: 70px;
  font-size: 12px;
}
</style>
